package com.boc.langxiang.ui.activity.shop;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.SpecialListView;
import com.boc.langxiang.entity.bean.PhotoBean;
import com.boc.langxiang.entity.bean.SpecialListInfo;
import com.boc.langxiang.entity.events.ZanEvent;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.entity.response.SpecialListContent;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.shop.SpecialListPresenter;
import com.boc.langxiang.ui.activity.BaseToolBarActivity;
import com.boc.langxiang.util.SnackBarUtil;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.R.attr.id;
import static com.boc.langxiang.R.id.item;

/**
 * 专题列表
 */
public class SpecialTopicActivity extends BaseToolBarActivity implements SpecialListView, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    private BaseQuickAdapter<SpecialListInfo> mAdapter;

    private SpecialListPresenter mPresenter;

    private int currentPage = 1;

    private View noMoreView, emptyView;

    private boolean mIsLoadMore;
    private boolean mIsOnRefresh;

    private final int _DetailRequest = 1001;

    private Runnable refreshingRunnable = new Runnable() {
        @Override
        public void run() {
            swipeRefresh.setRefreshing(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_special_topic);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initViews();
    }

    private void initViews() {
        initAdapter();
        mAdapter.openLoadMore(5, true);
        mAdapter.setOnLoadMoreListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsOnRefresh) {
                    return true;
                }
                return false;
            }
        });

        swipeRefresh.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        swipeRefresh.setOnRefreshListener(this);
        noMoreView = getLayoutInflater().inflate(R.layout.view_load_done, recyclerView, false);
        emptyView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation();
        mAdapter.isFirstOnly(true);

        mAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mContext, SpecialTopicDetailActivity.class);
                SpecialListInfo specialListInfo = mAdapter.getData().get(position);
                intent.putExtra("id", specialListInfo.getId());
                intent.putExtra("title", specialListInfo.getTitle());
                intent.putExtra("content", specialListInfo.getContent());
                startActivity(intent);
            }
        });
        initData();
    }

    private void initData() {
        mPresenter = new SpecialListPresenter(this);
        onRefresh();
    }

    private void initAdapter() {
        mAdapter = new BaseQuickAdapter<SpecialListInfo>(R.layout.special_topic_item, new ArrayList<SpecialListInfo>()) {
            @Override
            protected void convert(final BaseViewHolder helper, final SpecialListInfo item) {
                helper.setText(R.id.title_tv, item.getTitle());
                helper.setText(R.id.author_tv, "by" + "\t" + item.getAuthor());

                List<PhotoBean> photo = item.getPhoto();
                PicassoImageLoader.getInstance().displayUrlImage(mContext, null
                        , (ImageView) helper.getView(R.id.iv_cover));
                if (photo != null) {
                    PhotoBean photoBean = photo.get(0);
                    if (photoBean != null) {
                        String url = photoBean.getUrl();
                        if (!StringUtil.isEmpty(url)) {
                            PicassoImageLoader.getInstance().displayUrlImage(mContext, url
                                    , (ImageView) helper.getView(R.id.iv_cover));
                        }
                    }
                }

                String account_photo = item.getAccount_photo();
                PicassoImageLoader.getInstance().displayUrlImage(mContext, null
                        , (ImageView) helper.getView(R.id.head));
                if (!StringUtil.isEmpty(account_photo)) {
                    PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getAccount_photo()
                            , (ImageView) helper.getView(R.id.head));
                }

                helper.setText(R.id.like_count, String.valueOf(item.getClick_num()));
                helper.setText(R.id.check_count, String.valueOf(item.getClick()));

                helper.getView(R.id.like_layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SnackBarUtil.getInstance(helper.getConvertView()).showShort("点赞").setMessageColor(Color.RED).show();
                    }
                });
            }
        };
    }

    @Override
    protected boolean isSetTypeFace() {
        return true;
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        setToolBarTitle("专题");
        toolbar.setNavigationIcon(R.drawable.icon_return_black);
    }

    @Override
    public void getListSuccess(BaseResponse<SpecialListContent> response) {
        mIsOnRefresh = false;
        if (response.getContent().getRes() != null && response.getContent().getRes().size() > 0) {
            mAdapter.setNewData(response.getContent().getRes());
            if (response.getContent().getRes().size() < 5) {
                mAdapter.addFooterView(noMoreView);
                mAdapter.notifyDataChangedAfterLoadMore(false);
            }
        }
    }

    @Override
    public void loadMoreSuccess(List<SpecialListInfo> list, int page) {
        mIsLoadMore = false;
        if (list != null) {
            if (list.size() > 0) {
                this.currentPage = page;
                if (list.size() < 5) {
                    mAdapter.addFooterView(noMoreView);
                    mAdapter.notifyDataChangedAfterLoadMore(list, false);
                } else {
                    mAdapter.addFooterView(noMoreView);
                    mAdapter.notifyDataChangedAfterLoadMore(list, true);
                }
            } else {
                mAdapter.addFooterView(noMoreView);
                mAdapter.notifyDataChangedAfterLoadMore(false);
            }
        } else {
            mAdapter.addFooterView(noMoreView);
            mAdapter.notifyDataChangedAfterLoadMore(false);
        }
    }

    @Override
    public void showLoading() {
        swipeRefresh.post(refreshingRunnable);
    }

    @Override
    public void hideLoading() {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(false);
            }
        });
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }

    @Override
    public void onRefresh() {
        if (mIsLoadMore || mIsOnRefresh) {
            hideLoading();
            return;
        }
        mIsOnRefresh = true;
        mPresenter.getList();
        currentPage = 1;
    }

    @Override
    public void onLoadMoreRequested() {
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                if (mIsLoadMore || mIsOnRefresh) {
                    return;
                }
                mIsLoadMore = true;
                int page = currentPage + 1;
                mPresenter.loadMore(page);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onZanEvent(ZanEvent event) {
        onRefresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
